package org.algorithm.二师兄.数组.三月.第四周;

/**
 * @author zhx
 * @date 2022-03-21 星期一18:25
 *
 * url: https://leetcode-cn.com/problems/trapping-rain-water/
 */
public class 接雨水 {


    public static void main(String[] args) {
        int[] height = {0,1,0,2,1,0,1,3,2,1,2,1};
        System.out.println(trap(height));
    }

    /**
     *  双指针， 计算面积， 保存到一个变量中， 如果右边比左边低或者左边比右边低， 按低的高度进行计算。
     */
    public static int trap(int[] height) {
        int sum = 0;
        int[] max_left = new int[height.length];
        int[] max_right = new int[height.length];

        for (int i = 1; i < height.length - 1; i++) {
            max_left[i] = Math.max(max_left[i - 1], height[i - 1]);
        }
        for (int i = height.length - 2; i >= 0; i--) {
            max_right[i] = Math.max(max_right[i + 1], height[i + 1]);
        }
        for (int i = 1; i < height.length - 1; i++) {
            int min = Math.min(max_left[i], max_right[i]);
            if (min > height[i]) {
                sum = sum + (min - height[i]);
            }
        }
        return sum;
    }


}
